<?php

/**
 * Description of ContattiController
 *
 * @author luigi.pastore
 * @created  16-mag-2011
 */
class PartnersController extends Classes_Controller
{
    public function init()
    {
	$this->model_partner	= new Classes_Partner();
	$this->model_province	= new Classes_Province();

	$this->partner_types = $this->application->getResource( 'PartnerTypes' );
	$this->contact_roles = $this->application->getResource( 'ContactRoles' );
	$this->province = $this->model_province->fetchAll();
	
	$this->layout->province = $this->province;
	$this->layout->partner_types = $this->partner_types;
	
    }
    
    public function indexAction()
    {
	$this->layout->content = array( 'script' => 'partners/index' );
    }
    
    public function nuovoAction()
    {
	if( $_POST['salva'] AND $_POST['salva'] !== '' )
	{
	    $this->layout->data = $_POST;
	    
	    // Validiamo server-side...
	    $errorMsg = $this->checkFormData( $_POST );

	    if( !$errorMsg )
	    {
		// Mapping...
		$data = array(
		    'partner_name'		=> $_POST['partner_name'],
		    'partner_types'		=> implode( ',', array_values( $_POST['partner_types'] ) ),
		    'partner_email'		=> $_POST['partner_email'],
		    'partner_phone'		=> $_POST['partner_phone_prefix'] .'/'. $_POST['partner_phone_number'],
		    'partner_fax'		=> $_POST['partner_fax_prefix'] .'/'. $_POST['partner_fax_number'],
		    'partner_city'		=> $_POST['partner_city'],
		    'partner_cap'		=> $_POST['partner_cap'],
		    'partner_loc'		=> $_POST['partner_loc'],
		    'partner_street'		=> $_POST['partner_street'],
		    'partner_street_number'	=> $_POST['partner_street_number'],
		    'partner_province_id'	=> $_POST['partner_province_id'],		    
		    'partner_notes'		=> $_POST['partner_notes'],		    
		    'partner_createdby'		=> $this->application->auth->user['user_id']
		);
		
		$model = new Classes_Partner( $data );

		if( is_numeric( $partner_id = $model->save()->partner_id ) )
		{
		    // Rimanda alla pagina di associazione contatti...
		    //return $this->layout->content = array( 'script' => 'partners/associa' );
		    header( 'Location: /admin/partners/associa/id/' . $partner_id );
		}
		else
		{
		    trigger_error( 'Errore Inserimento Partner' );
		}
	    }
	}

	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'partners/nuovo' );
    }

    public function editAction()
    {
	// Edit
	if( !is_null( $this->getParam( 'id' ) ) )
	{
	    // Fetch
	    $partner = $this->model_partner->fetchById( (int) $this->getParam( 'id' ) );
  
	    // Se non c'è il post lancia l'errore
	    if( !is_array( $partner ) )
	    {
		trigger_error( 'Errore Edit Contatto', E_USER_WARNING );
	    }
	    else
	    {
		// Format..
		list( $partner['partner_phone_prefix'], $partner['partner_phone_number'] ) = explode( '/', $partner['partner_phone'] );
		list( $partner['partner_work_prefix'], $partner['partner_work_number'] ) = explode( '/', $partner['partner_work'] );
		list( $partner['partner_mobile_prefix'], $partner['partner_mobile_number'] ) = explode( '/', $partner['partner_mobile'] );
		list( $partner['partner_fax_prefix'], $partner['partner_fax_number'] ) = explode( '/', $partner['partner_fax'] );
		
		# Assegniamo i dati del post al layout
		$this->layout->data = $partner;
	    }
	}
	
	if( $_POST['salva'] AND $_POST['salva'] !== '' )
	{
	    $this->layout->data = $_POST;
	    
	    // Validiamo server-side...
	    $errorMsg = $this->checkFormData( $_POST );

	    if( !$errorMsg )
	    {
		// Mapping...
		$data = array(
		    'partner_id'		=> $partner['partner_id'],
		    'partner_firstname'		=> $_POST['partner_firstname'],
		    'partner_lastname'		=> $_POST['partner_lastname'],
		    'partner_email'		=> $_POST['partner_email'],
		    'partner_phone'		=> $_POST['partner_phone_prefix'] .'/'. $_POST['partner_phone_number'],
		    'partner_email2'		=> $_POST['partner_email2'],
		    'partner_email3'		=> $_POST['partner_email3'],
		    'partner_work'		=> $_POST['partner_work_prefix'] .'/'. $_POST['partner_work_number'],
		    'partner_mobile'		=> $_POST['partner_mobile_prefix'] .'/'. $_POST['partner_mobile_number'],
		    'partner_fax'		=> $_POST['partner_fax_prefix'] .'/'. $_POST['partner_fax_number'],
		    'partner_city'		=> $_POST['partner_city'],
		    'partner_cap'		=> $_POST['partner_cap'],
		    'partner_loc'		=> $_POST['partner_loc'],
		    'partner_street'		=> $_POST['partner_street'],
		    'partner_street_number'	=> $_POST['partner_street_number'],
		    'partner_province_id'	=> $_POST['partner_province_id'],		    
		    'partner_notes'		=> $_POST['partner_notes'],		    
		    'partner_modifiedby'	=> $this->application->auth->user['user_id']
		);
		    
		$model = new Classes_partner( $data );

		if( is_numeric( $partner_id = $model->save()->partner_id ) )
		{
		    // Rimanda alla pagina di conferma e cancella file temporanei...
		    $this->layout->forward = 'contatti/rubrica';

		    return $this->layout->content = array( 'script' => 'completed' );
		}
		else
		{
		    trigger_error( 'Errore Edit Contatto' );
		}
	    }
	}

	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'contatti/edit' );	
    }
    
    public function vediAction()
    {
	if( is_null( $this->getParam( 'id' ) ) )
	{
	    trigger_error( 'Errore Associa Contatto' );
	}
	
	// Fetch
	$partner = $this->model_partner->fetchById( array( $this->getParam( 'id' ) ) );

	$this->roles		= $this->application->getResource( 'partnerRoles' );
	
	// Se non c'è il post lancia l'errore
	if( !is_array( $partner ) )
	{
	    trigger_error( 'Errore Associa Contatto', E_USER_WARNING );
	}
	else
	{
	    $partner = array_shift( $partner );
	    
	    # Assegniamo i dati del post al layout
	    $this->layout->data = $partner;
	}
	
	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'contatti/vedi' );		
    }

    public function contattiAction()
    {
        if( is_null( $this->getParam( 'id' ) ) )
	{
	    trigger_error( 'Errore Associa Contatto' );
	}
	
	// Fetch
	$partner = array_shift( $this->model_partner->fetchById( array( $this->getParam( 'id' ) ) ) );

        # Assegniamo i dati al layout
        $this->layout->data =  $partner;
        
	// Salviamo in sessione i valori precedenti, che verranno utilizzati
	// da AjaxController->selectRemContactLocation()
	$_SESSION['ContactPartner'] = count( $partner['partner_contacts'] )  ? array_keys( $partner['partner_contacts'] ) : array( );
	
        if( $_POST )
	{
            $roles = array();
	    
	    foreach( $_POST AS $key => $value )
	    {
		if( substr( $key, 0, 8 ) == 'contact_' )
		{
		    // Mapping...
		    $roles[] = array( 'fab_locations_location_id' => $partner['partner_id'], 'fab_contacts_contact_id' => substr( $key, 8 ), 'fab_contacts_role' => $value );
		}
	    }
	    
	    if( !$errorMsg )
	    {
		$model = new Classes_ContactPartner( array( 'fab_partners_partner_id' => $partner['partner_id'] ) );
		
		if(  $model->save( $roles ) === TRUE )
		{
		    // Rimanda alla pagina di conferma e cancella file temporanei...
		    $this->layout->forward = 'partners/archivio';

		    return $this->layout->content = array( 'script' => 'completed' );
		}
		else
		{
		    trigger_error( 'Errore Aggiunta Contatto' );
		}
	    }
        }
        
	$this->layout->errorMsg = $errorMsg;
	$this->layout->content	= array( 'script' => 'partners/partner-contatti' );	
    }


    public function rubricaAction()
    {
	$this->layout->partners = $this->model_partner->fetchAll();
	$this->layout->content = array( 'script' => 'partners/rubrica' );
    }
    
    private function checkFormData( $data )
    {
	if( !filter_var( $data['partner_name'], FILTER_SANITIZE_STRING ) )
	    $errorMsg['partner_name'] = sprintf( ERR_FORMAT, 'Denominazione' );

	if( !$data['partner_types'] )
	    $errorMsg['partner_types'] = ERR_EMPTY;

	/* Info Opzionali */
	if( $data['partner_email'] !== '' AND !filter_var( $data['partner_email'], FILTER_VALIDATE_EMAIL ) )
	    $errorMsg['partner_email'] = sprintf( ERR_FORMAT, 'Email' );

	if( $data['partner_cap'] !== '' AND ( ( strlen( $data['partner_cap'] ) != 0 AND strlen( $data['partner_cap'] ) != 5 ) OR ( !filter_var( $data['partner_cap'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/^[0-9]{5}$/" ) ) ) ) ) )
	    $errorMsg['partner_address'] = sprintf( ERR_FORMAT, 'CAP' );

	if( ( $data['partner_phone_prefix'] !== '' OR $data['partner_phone_number'] !== '' ) AND ( !filter_var( $data['partner_phone_prefix'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/^[0-9]*$/" ) ) ) OR !filter_var( $data['partner_phone_prefix'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/[0-9]*/" ) ) ) ) )
	    $errorMsg['partner_mobile'] = sprintf( ERR_FORMAT, 'Tel. Privato' );
	
	if( ( $data['partner_fax_prefix'] !== '' OR $data['partner_fax_number'] !== '' ) AND ( !filter_var( $data['partner_fax_prefix'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/^[0-9]*$/" ) ) ) OR !filter_var( $data['partner_fax_number'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/[0-9]*/" ) ) ) ) )
	    $errorMsg['partner_fax'] = sprintf( ERR_FORMAT, 'Fax' );	
	
	return $errorMsg ? $errorMsg : false;
    }
} 

